import * as API from '../../../api/orderApi';
import * as util from '../../../utils/util';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isShowModal: false,
    sortArr: [{
      text: '按节点事件树查看'
    }, {
      text: '按事件时间顺序查看'
    }],
    sortSelectIndex: 0, //默认按节点事件树查看
    orderId: '',
    nodeId: '',//从消息页跳过来得默认展开nodeId
    messageId: '',
    shareId: '',
    order: {},
    timeTreeEvent: [],
    nodes: [],
    goodNum: 0,
    sendNum: 0,
    signedNum: 0,
    sortEvent: [],
    expandAll: true,
    nodesLength: 0, //实际有多少节点
    scrollViewEventIds: {},
    pingHeight: 0,
    scrollTimer: null,
    loadData: function () { }

  },
  modalOpen: function () {
    this.setData({
      isShowModal: true
    })
  },
  hideMarker: function () {
    this.setData({
      isShowModal: false
    })
  },
  sortItemSelect: function (e) {
    this.setData({
      sortSelectIndex: e.detail.index,
      isShowModal: false
    });
    if (e.detail.index == 1) {
      this.checkScrollIntoView();
    }
  },
  // 从详情进来
  getData: function () {
    API.getnodeEventList({
      orderId: this.data.orderId
      // shareId: this.data.shareId
    }).then(res => {
      wx.stopPullDownRefresh();
      if (!res) return;
      this.setData({
        order: res.order,
        orderId: res.order.id
      });
      this.initData(res);
    }, err => {
      wx.stopPullDownRefresh();
      util.toast('读取订单数据失败，请稍后再试');
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1500);
    })
  },
  // 从消息进来
  getDataByMsg() {
    API.findOrderDetail({
      messageId: this.data.messageId
    }).then(res => {
      if (!res) return;
      API.markAsReadOne({
        messageId: this.data.messageId
      })
      this.setData({
        order: res.order,
        orderId: res.order.id
      });
      this.initData(res);
    }, err => {
      util.toast('读取订单数据失败，请稍后再试');
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1500);
    })
  },
  initData: function (res) {
    let nodes = [];
    let toOrdedEvents = [];
    let toOrdedEvents2 = [];
    let count = 0;
    let defaultNodes = {
      60: {
        _empty: true,
        nodeId: '60',
        events: []
      },
      50: {
        _empty: true,
        nodeId: '50',
        events: []
      },
      40: {
        _empty: true,
        nodeId: '40',
        events: []
      },
      30: {
        _empty: true,
        nodeId: '30',
        events: []
      },
      20: {
        _empty: true,
        nodeId: '20',
        events: []
      },
      10: {
        _empty: true,
        nodeId: '10',
        events: []
      }
    }
    res.nodeList.forEach(item => {
      let events = res.nodeEventMap['event' + item['nodeId']];
      defaultNodes[item['nodeId']] = {
        ...item,
        events: events
      };
      toOrdedEvents = toOrdedEvents.concat(events)
    })
    for (const key in defaultNodes) {
      if (defaultNodes.hasOwnProperty(key)) {
        nodes.push(defaultNodes[key])
      }
    }
    nodes = nodes.reverse();
    toOrdedEvents.sort((a, b) => {
      return b.date - a.date
    });
    if (!this.data.messageId) {
      // if (this.data.sortSelectIndex == 0) {
      outer: for (let i = 0; i < nodes.length; i++) {
        inner: for (let j = 0; j < nodes[i]['events'].length; j++) {
          if (count == 2)
            break outer;
          if (nodes[i]['events'][j]['date'] == toOrdedEvents[0]['date'] || nodes[i]['events'][j]['date'] == toOrdedEvents[1]['date']) {
            nodes[i]['events'][j]['defaultOpen'] = '1';
            nodes[i]['_expandCount'] ? ++nodes[i]['_expandCount'] : nodes[i]['_expandCount'] = 1;
            nodes[i]['_hasMore'] = nodes[i]['events'].length > nodes[i]['_expandCount'];
            nodes[i]['_expand'] = true;
            console.log('i', i)
            this.ajaxUpdateNodes({
              orderId: this.data.orderId,
              shardingId: this.data.order.shardingId,
              nodeId: nodes[i]['events'][j]['nodeId'],
              id: nodes[i]['events'][j]['id']
            })
            ++count;
          }
        }
      }
      // }
    }
    else {
      nodes.forEach(item => {
        if (item.nodeId == this.data.nodeId) {
          item._expand = true;
          if (this.data.nodeId == 'A1' || this.data.nodeId == 'A2')
            item.events[0]['defaultOpen'] = '1';
          if (item.events.length > 1)
            item._hasMore = true;

        }
      })

    }
    toOrdedEvents2 = util.deepClone(toOrdedEvents);
    toOrdedEvents2.forEach((item, i) => {
      if (i == 0)
        item['_isFirst'] = true;
      item['defaultOpen'] = '1';
    });
    //节点右上角加红点
    for (let i = 0; i < nodes.length; i++) {
      for (let j = 0; j < nodes[i]['events'].length; j++) {
        if (nodes[i]['events'][j]['readSign'] == '0') {
          nodes[i]['readSign'] = '0';
          break;
        }
      }
    }
    this.setData({
      nodes: nodes,
      nodesLength: res.nodeList.length,
      timeTreeEvent: toOrdedEvents2,
      goodNum: res.nodeEventMap.goodNum,
      sendNum: res.nodeEventMap.sendNum,
      signedNum: res.nodeEventMap.signedNum
    });
    this.showAllOrHideAll();

  },
  toggleData: function (idx, flag) {
    let expand_key = "nodes[" + idx + "]._expand";
    let events_key = "nodes[" + idx + "].events";
    let hasmore_key = "nodes[" + idx + "]._hasMore";
    let events = this.data.nodes[idx]['events'];
    let expand = this.data.nodes[idx]['_expand'];
    //let hasMore = this.data.nodes[idx]['_hasMore'];
    events.forEach(item => {
      item.defaultOpen = typeof flag == 'boolean' ? flag : (expand ? '0' : '1');
    });
    this.setData({
      [expand_key]: (typeof flag == 'boolean' ? flag : (expand ? false : true)),
      [events_key]: events,
      [hasmore_key]: false
    });
  },
  toggle: function (e) {
    let idx = e.currentTarget.dataset.idx;
    let isMoreCLick = e.currentTarget.dataset.ismore;
    let expand = this.data.nodes[idx]['_expand'];
    let token = wx.getStorageSync('token');
    let ret = [];
    let postBody = {
      orderId: this.data.orderId,
      shardingId: this.data.order.shardingId,
      nodeId: this.data.nodes[idx]['nodeId'],
    };
    if (isMoreCLick) { //点击更多
      this.toggleData(idx, true);
    } else {
      this.toggleData(idx);
    }
    if (!expand && token) { //点击展开
      this.ajaxUpdateNodes(postBody);
    };
    this.showAllOrHideAll()
  },
  ajaxUpdateNodes: function (postBody) {
    API.updateNodeStatus(postBody).then(res => {

    }, err => {
      util.toast('读取订单数据失败，请稍后再试');
      setTimeout(() => {
        wx.navigateBack({
          delta: 1
        })
      }, 1500);
    })
  },
  toggleAll: function () {
    let expandAll = this.data.expandAll;
    let postBody = {
      orderId: this.data.orderId,
      shardingId: this.data.order.shardingId
    }
    this.data.nodes.forEach((item, idx) => {
      this.toggleData(idx, expandAll);
    });
    if (expandAll) //点击展开
      this.ajaxUpdateNodes(postBody);
    this.setData({
      expandAll: !expandAll
    })
  },
  isExpandAll: function () {
    let arr = this.data.nodes.filter(item => {
      return item['_expand']
    });
    return arr.length == this.data.nodesLength;
  },
  showAllOrHideAll: function () {
    let flag = false;
    let arr = this.data.nodes.filter(item => {
      return item['_expand']
    });
    flag = arr.length == this.data.nodesLength;
    if (flag)
      this.setData({
        expandAll: false
      })
    else
      this.setData({
        expandAll: true
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showNavigationBarLoading();
    if (options.messageId) {
      this.setData({
        messageId: options.messageId,
        nodeId: options.nodeId || '',
        loadData: this.getDataByMsg.bind(this)
      });

    } else {
      this.setData({
        orderId: options.orderId,
        shareId: options.shareId || '',
        loadData: this.getData.bind(this)
      })
    }
    wx.hideShareMenu();
    this.data.loadData();
    this.data.pingHeight = wx.getSystemInfoSync().windowHeight;
  },

  nagBack() {
    wx.navigateTo({
      // url: '/pages/order/orderDetail/orderDetail?id=' + this.data.orderId + '&hiddenPrice=' + this.data.isHiddenPrice
      url: '/pages/order/orderDetail/orderDetail?id=' + this.data.orderId
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setTimeout(() => {
      wx.hideNavigationBarLoading();
    }, 1200)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  onPageScroll: function (e) {
    // this.setData({
    //   scrollTop: e.scrollTop
    // })
    if (this.data.sortSelectIndex == 1)
      this.checkScrollIntoView()
  },
  checkScrollIntoView: function () {
    console.log(this.data.scrollTimer)
    if (this.data.scrollTimer) {
      console.log('clear');
      clearTimeout(this.data.scrollTimer);
      this.setData({
        scrollTimer: null
      });
    }
    this.data.scrollTimer = setTimeout(x => {
      let query = wx.createSelectorQuery();
      query.selectAll('.scroll-view').boundingClientRect((rect) => {
        console.log(rect)
        rect.map((item) => {
          let pingHeight = this.data.pingHeight;
          let bottomLine = item.top + item.height - 35;
          if ((item.top + item.height <= pingHeight) && bottomLine > 0) {
            if (item.dataset.readsign == "0") {
              this.data.scrollViewEventIds[item['dataset']['eventId']] = item['dataset']['nodeId'];
            }
          }
        });
        console.log(this.data.scrollViewEventIds)
        for (const key in this.data.scrollViewEventIds) {
          if (this.data.scrollViewEventIds.hasOwnProperty(key)) {
            let item = this.data.scrollViewEventIds[key];
            this.ajaxUpdateNodes({
              orderId: this.data.orderId,
              shardingId: this.data.order.shardingId,
              nodeId: item,
              id: key
            })
          }
        }
      }).exec();
    }, 250);


  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.data.loadData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})